<template>
	<SkeletonScreen v-if="loading"></SkeletonScreen>
	<view class="container">
		<!-- 用户信息部分 -->
		<view class="user-info">
			<!-- {{users.openId}} -->
			<text class="username">ئابونىت ئۇچۇرى : {{ users.openId }} </text>
			<text class="expire-info">SVIP ۋاقتى : {{ timeStatus }} ئەزالىق ۋاقتى توشىدۇ ، ئەزالىق سىتىۋالسىڭىز ۋاقتى
				ئۇزارتىلىدۇ !</text>
		</view>

		<!-- 分割线 -->
		<view class="divider"></view>

		<!-- 会员类型标题 -->
		<view class="section-title">
			<text>VIP ئەزا</text>
			<text class="subtitle">تۈندىدار ، توركۆرگۈچ ، كومپىيىتۇردا ئورتاق ئىشلەيدۇ !</text>
		</view>

		<!-- 会员选项 -->
		<view class="membership-options">

			<!-- 连续包年选项 -->
			<view class="option-card" v-for="(item, index) in coinAlpayValue"
				:class="{ 'active': selectedOption === index }" @click="selectOption(index)">
				<view class="option-header">
					<text class="option-title">گۈزەل مىنۇتلاردىن تەڭ بەھىرلىنەيلى </text>
					<text class="option-type">{{ item.name }}</text>
				</view>
				<view class="option-price">
					<text class="current-price">¥{{ item?.currentPrice }}</text>
					<text class="original-price">¥{{ item?.originalPrice }}</text>
				</view>
				<view class="corner-tag" v-if="selectedOption === index">¥&nbsp;{{ discountAmount }} كىمەيتىلدى</view>
			</view>

		</view>

		<!-- 会员权限提示 -->
		<view class="privileges-section">
			<view class="section-header">
				<text class="title"> ئەزا ھوقۇقلىرى</text>
				<text class="subtitle">ئەزالىق ئاچقۇزغاندىن كىيىن تۆۋەندىكى ھوقۇقلاردىن بەھرىمان بولالايسىز </text>
			</view>

			<view class="privileges-grid">
				<view class="privilege-item" v-for="item in privileges" :key="item.id">
					<image class="privilege-icon" :src="item.icon" mode="aspectFit"></image>
					<text class="privilege-text">{{ item.text }}</text>
				</view>
			</view>
		</view>

		<!-- 底部支付按钮 -->
		<view class="payment-footer">
			<view class="price-info">
				<text>كىلىشىمگە قوشۇلۇش ۋە پۇل تۆلەش</text>
				<text class="price">¥{{ currentPrice.coinAlpayValue }}</text>
			</view>
			<text class="discount-info">¥{{ discountAmount }} كىمەيتىلدى</text>
			<navigator url="/pages/alpay/content/content" class="agreement-text">ئەزالىق ئاچقۇزۇشتىن بۇرۇن <ئۈندىدار
					ئەزالىق سىتىۋىلىش كىلىشىمى> چۈشۈنۈڭ</navigator>
			<button class="payment-button" @click="handlePayment">سىتىۋىلىش</button>
		</view>

	</view>
</template>

<script setup>
import {
	ref,
	computed
} from 'vue';
import {
	coinAlpay,
	wechatJsapiPay,
	checkPayResult
} from '@/API/alpayApis.js';
import {
	loginUpdateStatus,
	loginStatus,
	loginById
} from '@/API/geidApis.js';
import { wechatPayment, handlePaymentResult } from '@/utils/wechat-payment.js';
const coinAlpayValue = ref([]); //金额
const loading = ref(true)

const users = ref([]);
const timeStatus = ref('2020-09-20 12:20');

// 当前选中的选项
const selectedOption = ref(0);

// 会员金额
const coinAlpayFunction = async () => {
	let res = await coinAlpay();
	coinAlpayValue.value = res.data;
	console.log("金额：", res.data);
	let user = uni.getStorageSync("user");
	users.value = user;
	timeStatus.value = formatTimestamp(user.statusCreate);
	loading.value = false
}
// 会员金额
coinAlpayFunction();

// 时间码转换
function formatTimestamp(timestamp) {
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
	const day = String(date.getDate()).padStart(2, '0');
	const hour = String(date.getHours()).padStart(2, '0');
	const minute = String(date.getMinutes()).padStart(2, '0');

	return `${year}-${month}-${day} ${hour}:${minute}`;
}


// 计算当前价格
const currentPrice = computed(() => {
	const coin = [];
	coin.coinAlpayValue = coinAlpayValue?.value[selectedOption.value]?.currentPrice;
	coin.coinDays = coinAlpayValue?.value[selectedOption.value]?.days;
	return coin;
})

// 计算折扣金额
const discountAmount = computed(() => {
	const option = coinAlpayValue?.value[selectedOption.value];
	return option?.originalPrice - option?.currentPrice;
})

// 选择会员选项
const selectOption = (option) => {
	selectedOption.value = option;
	uni.pageScrollTo({
		scrollTop: 800
	})
}

// 处理支付（优化版）
const handlePayment = async () => {

	try {
		// 检查基本参数
		const days = currentPrice.value.coinDays;
		const paymentAmount = currentPrice.value.coinAlpayValue;
		const user = uni.getStorageSync("user");
		const openid = user.openId;
		// 验证用户登录
		if (!user) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			return;
		}

        // 调用微信支付
        const result = await wechatPayment({
          days: days,
          amount: paymentAmount,
          openid: openid
        });
        
        // 处理支付结果
        const success = handlePaymentResult(result);
        
        if (success) {
          // 支付成功后的逻辑
          checkPayStatus(user.id, days, paymentAmount);
        }
        
      } catch (error) {
        console.error('支付错误:', error);
        let errorMessage = '支付失败';
        
        if (error.message) {
          if (error.message.includes('cancel')) {
            errorMessage = '用户取消支付';
          } else if (error.message.includes('permission')) {
            errorMessage = '支付权限验证失败';
          } else if (error.message.includes('不可用')) {
            errorMessage = '支付功能未就绪';
          }
        }
        uni.showToast({ title: errorMessage, icon: 'none' });
      }
}

// 查询支付状态
const checkPayStatus = async (userId, days, totalFee) => {
	uni.showLoading({
		title: '用户信息更新中...',
		mask: true
	});

	let now = new Date();
	// 创建一个新的日期对象，增加一n天
	let oneDayLater = new Date(now);
	oneDayLater.setDate(now.getDate() + days);
	console.log("time个天后的时间戳是：" + oneDayLater.getTime());
	const result = await loginUpdateStatus(userId, oneDayLater.getTime());
	uni.removeStorageSync('user');
	uni.hideLoading();
	uni.setStorageSync('user', result);
	users.value = {};
	users.value = result;
	timeStatus.value = formatTimestamp(result.statusCreate);
	uni.showToast({
		title: '更新完成！',
	});


	const shareUserId = uni.getStorageSync('ShareUserId')
	if (shareUserId > 0) {
		uni.request({
			url: 'https://min.erkantv.cn:8083/h5/openId/money',
			method: 'GET',
			data: {
				userId: shareUserId,
				money: totalFee / 2,
				close: true
			},
			success: (e) => {
				console.log("给推荐用户分红成功！")
				uni.removeStorageSync('ShareUserId')
			}
		})
	}



}

// 会员特权数据
const privileges = ref([{
	id: 1,
	text: 'ئىلانسىز',
	icon: '/static/coin_icon/mian.png'
},
{
	id: 2,
	text: 'يۇقرى ئىنىقلىق',
	icon: '/static/coin_icon/gao.png'
},
{
	id: 3,
	text: 'چەكلىمىسىز كۆرۈش',
	icon: '/static/coin_icon/camera.png'
},
{
	id: 4,
	text: 'مەخسۇس مەزمۇنلار',
	icon: '/static/coin_icon/hui.png'
},
{
	id: 5,
	text: 'ئورتاق ئىشلىتىش',
	icon: '/static/coin_icon/duo.png'
},
{
	id: 6,
	text: 'ئالدىن كۆرۈش',
	icon: '/static/coin_icon/eye.png'
},
])
</script>

<style lang="scss">
.container {
	padding: 20rpx 30rpx;
	background-color: #000;
	// min-height: 100vh;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	height: 100%;
}

.user-info {
	display: flex;
	flex-direction: column;
	padding: 20rpx 0;
	direction: rtl;

	.username {
		font-size: 32rpx;
		color: #fff;
		font-weight: bold;
		padding-left: 20rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.expire-info {
		font-size: 26rpx;
		color: #888;
		margin-top: 10rpx;
	}
}

.divider {
	height: 1rpx;
	background-color: #333;
	margin: 20rpx 0;
}

.section-title {
	display: flex;
	flex-direction: column;
	margin-bottom: 30rpx;
	direction: rtl;

	text {
		font-size: 34rpx;
		color: #fff;
		font-weight: bold;
	}

	.subtitle {
		font-size: 26rpx;
		color: #888;
		font-weight: normal;
		margin-top: 10rpx;
	}
}

.membership-options {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	flex: 1;
}

.option-card {
	background-color: #1d1d1d;
	border-radius: 16rpx;
	padding: 30rpx;
	position: relative;
	overflow: hidden;
	transition: all 0.3s ease;
	border: 2rpx solid #333;

	&.active {
		border-color: #ff0000;
		background-color: #1d1d1d;
		transform: translateY(-5rpx);
		box-shadow: 0 10rpx 20rpx rgba(255, 0, 0, 0.2);

		.option-type {
			color: #ff0000 !important;
		}
	}

	.option-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.option-title {
			font-size: 30rpx;
			color: #fff;
		}

		.option-type {
			font-size: 28rpx;
			color: #ff3333;
			font-weight: bold;
		}
	}

	.option-price {
		display: flex;
		align-items: flex-end;

		.current-price {
			font-size: 42rpx;
			color: #ff0000;
			font-weight: bold;
		}

		.original-price {
			font-size: 28rpx;
			color: #666;
			text-decoration: line-through;
			margin-left: 15rpx;
			margin-bottom: 4rpx;
		}
	}

	.corner-tag {
		position: absolute;
		right: 0;
		top: 0;
		background-color: #ff0000;
		color: #fff;
		font-size: 22rpx;
		padding: 6rpx 20rpx;
		border-bottom-left-radius: 16rpx;
		transform: translateY(-5rpx);
		animation: bounceIn 0.5s;
	}
}

/* 新增的会员特权区域样式 */
.privileges-section {
	background-color: #1d1d1d;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-top: 40rpx;
	direction: rtl;

	.section-header {
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;

		.title {
			font-size: 32rpx;
			color: #fff;
			font-weight: bold;
		}

		.subtitle {
			font-size: 26rpx;
			color: #888;
			margin-top: 10rpx;
		}
	}

	.privileges-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 30rpx;

		.privilege-item {
			display: flex;
			align-items: center;

			.privilege-icon {
				width: 40rpx;
				height: 40rpx;
				margin-left: 15rpx;
			}

			.privilege-text {
				font-size: 28rpx;
				color: #fff;
			}
		}
	}
}

.payment-footer {
	background-color: #1d1d1d;
	padding: 30rpx;
	border-radius: 16rpx;
	margin-top: 40rpx;
	box-shadow: 0 -5rpx 20rpx rgba(0, 0, 0, 0.3);


	.price-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15rpx;

		text {
			font-size: 32rpx;
			color: #fff;
		}

		.price {
			font-size: 40rpx;
			color: #ff0000;
			font-weight: bold;
		}
	}

	.discount-info {
		display: block;
		font-size: 26rpx;
		color: #ff0000;
		text-align: right;
		margin-bottom: 30rpx;
	}

	.agreement-text {
		display: block;
		font-size: 24rpx;
		color: #ff0000;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.payment-button {
		background-color: #ff0000;
		color: #fff;
		border-radius: 50rpx;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 34rpx;
		font-weight: bold;
		transition: all 0.3s;

		&:active {
			opacity: 0.9;
			transform: scale(0.98);
			background-color: #cc0000;
		}
	}
}

@keyframes bounceIn {
	0% {
		opacity: 0;
		transform: scale(0.3) translateY(-5rpx);
	}

	50% {
		opacity: 1;
		transform: scale(1.05) translateY(-5rpx);
	}

	100% {
		transform: scale(1) translateY(-5rpx);
	}
}
</style>